<?php
require 'includes/config.php';
require 'includes/auth.php';
require 'includes/sanitize.php';
$data = sanitize($_GET);
if(isset($data['submit']) && $data['playerid'] != "" && $data['teamid'] != ""){
	// Add players to specific team
	$request = new makeRequest($backend.'api.php', 'POST', 'method=team&auid='.$_SESSION['uid'].
	'&accesstoken='.$_SESSION['accesstoken'].'&newplayer='.$data['playerid'].'&id='.$data['teamid']);
	$request = $request->makeRequest();
	$http_code = $request [1];
	if($http_code != 200){
		$error = "Error, http code: ".$http_code;
	}
}

// Get list with all teams owned by current user
$request = new makeRequest($backend.'api.php?method=team&owner='.$_SESSION['uid'], 'GET');
$request = $request->makeRequest();
$rbody = $request[0];
$http_code = $request [1];
$obj = json_decode($rbody);
if($http_code == 200 && $obj[0]->{'id'} != ""){
	// Beginning of table
	$msg.="<table border='1'><tr>
	<th>Team name</th>
	<th>League</th>
	<th>LW</th>
	<th>CE</td>
	<th>RW</th>
	<th>RD</th>
	<th>LD</th>
	<th>G</th>
	<th>Points</th>
	<th>Drafts</th>
	<th>Bank</th></tr>";
	// For all the teams, get player names
	foreach($obj as &$value){
		$msg.="<tr><td>".$value->{'name'}."</td>";
		// Resolve league id to league name
		$request = new makeRequest($backend.'api.php?method=league&id='.$value->{'league'}, 'GET');
		$tmp = $request->makeRequest();
		$rbody = $tmp[0];
		$http_code = $tmp[1];
		$obj2 = json_decode($rbody);
		$msg.= "<td><a href='http://kabanja.se/manager/viewleague.php?id=".$obj2[0]->{'id'}."'>".$obj2[0]->{'name'}."</a></td>";
		// Make array with all player ids
		$playerids= array($value->{'lw'},$value->{'ce'},$value->{'rw'},$value->{'rd'},$value->{'ld'},$value->{'gk'});
		// Resolv player id to name one by one
		foreach($playerids as &$value2){
			// Request playerinfo
			$request = new makeRequest($backend.'api.php?method=player&id='.$value2, 'GET');
			$tmp = $request->makeRequest();
			$rbody = $tmp[0];
			$http_code = $tmp[1];
			$obj2 = json_decode($rbody);
			// Insert player name into the table
			$msg.= "<td><a href='viewplayers.php?playerid=".$value2."'>".$obj2[0]->{'firstname'}." ".$obj2[0]->{'lastname'}."</a></td>";
		}
		$msg.= "<td>".$value->{'points'}."</td>
		<td>".$value->{'drafts'}."</td>
		<td>".$value->{'bank'}."</td></tr>";
	}
	$msg.="</table>";
}else{
	$msg = "Error, no teams to display";
}


require 'includes/header.php';
require 'includes/topmenu.php';
echo '<div id="kaka">';
require 'includes/sidemenu.php';
echo '<div id="content">';
echo '<div id="info">';
if(isset($error) && $error != ""){
	echo $error;
}
echo $msg;
echo '</div>';
require 'includes/footer.php';
?>

</body>
</html>
